package com.quanyan.orderpay.web;

import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.quanyan.alipay.config.AlipayConfig;
import com.quanyan.alipay.protocal.AliPayTradeQueryReq;
import com.quanyan.alipay.protocal.AliPayTradeQueryResp;
import com.quanyan.alipay.protocal.AliRespQueryTrade;
import com.quanyan.alipay.sign.RSA;
import com.quanyan.alipay.util.AlipayNotify;
import com.quanyan.api.APIRequest;
import com.quanyan.api.APIResponse;
import com.quanyan.common.Plugin.Page;
import com.quanyan.common.encrypt.AESCoder;
import com.quanyan.common.http.HttpClientUtils;
import com.quanyan.common.utils.CommonUtils;
import com.quanyan.common.utils.StringUtil;
import com.quanyan.order.entity.Order;
import com.quanyan.order.entity.OrderExample;
import com.quanyan.order.mapper.OrderMapper;
import com.quanyan.orderpay.component.OrderPayRedisTemplate;
import com.quanyan.orderpay.entity.BackInfo;
import com.quanyan.orderpay.request.*;
import com.quanyan.orderpay.response.RespPreOrder;
import com.quanyan.orderpay.service.OrderPayService;
import com.quanyan.pay.component.alipay.AlipayComponent;
import com.quanyan.pay.entity.*;
import com.quanyan.pay.enums.PayWayEnum;
import com.quanyan.pay.enums.RefundStatusEnum;
import com.quanyan.pay.mapper.EWithdrawApplyMapper;
import com.quanyan.pay.mapper.PayRecordMapper;
import com.quanyan.pay.mapper.TSNRecordMapper;
import com.quanyan.pay.service.AccountService;
import com.quanyan.pay.service.PayConfigService;
import com.quanyan.pay.web.request.ReqAlipayAccount;
import com.quanyan.redisCluster.utils.RedisConstants;
import com.quanyan.redisCluster.utils.RedisKey;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

/**
 * Created by wmb on 2016/11/9.
 */
@RestController
@RequestMapping(value="/api/pay/test")
public class Test {
    @Autowired
    private OrderPayService orderPayService;
    @Autowired
    private PayConfigService payConfigService;
    @Autowired
    private AlipayComponent alipayComponent;
    @Autowired
    private OrderMapper orderMapper;
    @Value("${wechat.pay.callback}")
    private String callBack;
    private AlipayNotify alipayNotify;
    @Autowired
    private AccountService accountService;
    @Autowired
    private OrderPayRedisTemplate orderPayRedisTemplate;
    @Autowired
    private PayRecordMapper payRecordMapper;
    @Autowired
    private TSNRecordMapper tsnRecordMapper;
    @Autowired
    private EWithdrawApplyMapper eWithdrawApplyMapper;
    @RequestMapping(value="/verify",method= RequestMethod.POST)
    public ResponseEntity<Object> verify(){
        String map = "{\"body\":\"我也不知道买了什么\",\"open_id\":\"20881022051391249599429820716907\",\"subject\":\"我也不知道买了什么\",\"sign_type\":\"RSA\",\"buyer_logon_id\":\"186****4372\",\"auth_app_id\":\"2016070701589069\",\"notify_type\":\"trade_status_sync\",\"out_trade_no\":\"30974977595600081017\",\"version\":\"1.0\",\"point_amount\":\"0.00\",\"fund_bill_list\":\"[{\\\"amount\\\":\\\"0.01\\\",\\\"fundChannel\\\":\\\"PCREDIT\\\"}]\",\"total_amount\":\"0.01\",\"buyer_id\":\"2088702612944072\",\"trade_no\":\"2017040721001004070292191218\",\"notify_time\":\"2017-04-07 13:50:05\",\"charset\":\"UTF-8\",\"invoice_amount\":\"0.01\",\"trade_status\":\"TRADE_SUCCESS\",\"gmt_payment\":\"2017-04-07 13:50:05\",\"sign\":\"Li7sDWbbk3cNPvYNbqfbf+8CZOYUwna5qGIfUWbdpMd90xm+UPAD4YTf3Ho7Rnbx8977z6HWEKldgK1wud3bgY67fK/HiC9ZcKypFQjAEovihIVBTbxptRUyTRhxWbiLp5gAVYiiDx5c51QUyd/BGie1vdEAueTF5vJoWC21GzY=\",\"gmt_create\":\"2017-04-07 13:50:01\",\"buyer_pay_amount\":\"0.01\",\"receipt_amount\":\"0.01\",\"app_id\":\"2016070701589069\",\"seller_id\":\"2088421220279210\",\"notify_id\":\"6a34b1bfa57235b4c6a2fd6408394b0gji\",\"seller_email\":\"financial6@quncaotech.com\"}";
        String config = "{\"partner\":\"2088421220279210\",\"private_key\":\"MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAMwHbr+gPAE9hP/0\\nkr3opWcShYx16RUKiqgT1lvC0Rivx72ddvY0cmygAZg3FUfn4vg4MT+fVOGQqihU\\nit+wrjt8PWy9qjFBTCXfayV/THgekcT+eztyItUXLM1ueauSGbNa2NFyMxjb43oC\\nUnapVG2euH9INITk/afC+pzXnlKHAgMBAAECgYEAquhm+xpMaXWRHZ9P9MkXFLpN\\nKJX0w21rLNRBMeiFozpMBSgMaL0SRK/b5hfuOaejVu4rQvJC9hhqkRIQqsSjjS1D\\nguzL1K+l1Zn2YQAaBzKuuyszbTCcge/aBp0SM+vHJUr+F/jjkDszeJcmKTJEWLG6\\nIApqnFE8oNRHVd9s0jECQQDyK67/gAlyz3f1MaSZ1iH2/zFziYh/fre1UUS60usC\\n2/4fNdHSboMv+gOlrua+ScvhmN9mylrX1MO8K6F7N/tDAkEA164nNEVARaqf6FwE\\nFqBMmd4mFEqDKyasHJJufU/hr9waMMF0OjJGweVI/HFsAnGNpj35QxijjmjjWdJp\\nzOtdbQJBAMsFMDpmfoVPxQM70QBe8i59llmD7XjlJOHO9c2h0P+eqpZDqlm96CEq\\nejBGRo80ksXYQUGNV0clycpQ0ZnZPr0CQANlcqiYDpMKRMpb6JSSoaIqpV7cbYRY\\nb41joOnIQD2Msbzizvm7oPGcsrGG97RyJVDg2PP9h1XOwQXBEnlvm2ECQGDWk1uY\\ne8p8Pl5ZJxCXT+6uxBNtq+PYkNxm2Kzegk+D6AIgGW5bdXTFAmh0yEf1r1m5JmIg\\nV7g0m/wJ52PE3q8=\",\"ali_public_key\":\"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCnxj/9qwVfgoUh/y2W89L6BkRAFljhNhgPdyPuBV64bfQNN1PjbCzkIM6qRdKBoLPXmKKMiFYnkd6rAoprih3/PrQEB/VsW8OoM8fxn67UDYuyBTqA23MML9q1+ilIZwBC2AQ2UBVOrFXfFl75p6/B5KsiNG9zpgmLCUYuLkxpLQIDAQAB\",\"input_charset\":\"UTF-8\",\"sign_type\":\"RSA\",\"seller\":\"financial6@quncaotech.com\",\"key\":\"s23d6wuq33jv592oa08mnhoadfxk4sat\"}";
        Gson gson = new GsonBuilder().create();
        java.lang.reflect.Type type = new TypeToken<AlipayConfig>() {
        }.getType();
        java.lang.reflect.Type type1 = new TypeToken<Map<String, String>>() {
        }.getType();
        AlipayConfig alipayConfig = gson.fromJson(config, type);
        alipayConfig.open_public_key = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDDI6d306Q8fIfCOaTXyiUeJHkrIvYISRcc73s3vF1ZT7XN8RNPwJxo8pWaJMmvyTn9N4HQ632qJBVHf8sxHi/fEsraprwCtzvzQETrNRwVxLO5jVmRGi60j8Ue1efIlzPXV9je9mkjzOmdssymZkh2QhUrCmZYI/FCEa3/cNMW0QIDAQAB";
        Map<String, String> map1 = gson.fromJson(map, type1);
        boolean flag = AlipayNotify.verify(map1, alipayConfig);
        return new ResponseEntity<Object>(flag, HttpStatus.OK);
    }
    @RequestMapping(value="/test2",method= RequestMethod.POST)
    public ResponseEntity<Object> test2(){
        String userString = CommonUtils.zeroFill(1 % 1000000 + "", 6);
        String random = "random" + StringUtils.leftPad(ThreadLocalRandom.current().nextInt(100)+"", 2, "0");
        random = random + "系统时间:"+ CommonUtils.getSysRunMillis();
        random = random + "user:"+ userString;
        return new ResponseEntity<Object>(random, HttpStatus.OK);
    }
    @RequestMapping(value="/wxscan",method= RequestMethod.POST)
    public ResponseEntity<Object> test(HttpServletRequest request,@RequestBody ReqOrderSave test){
        APIRequest<ReqOrderSave> reqOrderSaveAPIRequest = new APIRequest<>();
        ReqOrderSave reqOrderSave = new ReqOrderSave();
        reqOrderSaveAPIRequest.setData(reqOrderSave);

        reqOrderSave.setSourceBusinessId("PLACE_BOOKING_BUSINESS_CODE");
        reqOrderSave.setSourceSystemId("PLACE_SYSTEM_CODE");
        reqOrderSave.setChannelId(1);
        reqOrderSave.setContactMobile("13888888888");
        reqOrderSave.setContactName("制哥");
        reqOrderSave.setExtraParam("拓展字段原样返回");
        reqOrderSave.setMchId(2); //此处为城市ID
        reqOrderSave.setNotifyURL(callBack);
        reqOrderSave.setOrderAmount(test.getOrderAmount());  //订单金额100元.
        reqOrderSave.setOrderDescribe("我也不知道买了什么");
        reqOrderSave.setOrderURL("订单缩略图URL");
        reqOrderSave.setOutTradeNo(test.getOutTradeNo());
        reqOrderSave.setPayNote("速不要辣椒");
        reqOrderSave.setUserClientIp("");
        reqOrderSave.setPayTimeOut(1);
        reqOrderSave.setPayConfirmNotifyURL("http://192.168.32.178:30000/api/place/callback/payConfirmCallback");
        reqOrderSave.setUid(810);
        reqOrderSave.setShowURL("订单中心展现的商品详情URL");
        reqOrderSave.setBuyerAccount("o5p0hwDiTg8Q8TTkW6GYtlWZVcPA");
        reqOrderSave.setUserClientIp("10.46.131.91, 61.50.248.5");
        // reqOrderSave.setBuyerAccount("oL_y9s22C1flAfP3v7dF3caRWVDg");
        reqOrderSave.setService("service.pay");
        reqOrderSave.setAuthCode(test.getAuthCode());

        List<ReqProductDetail> reqProductDetailList = new ArrayList<>();
        ReqProductDetail reqProductDetail = new ReqProductDetail();
        reqProductDetail.setShowURL("产品详情URL:http://www.baidu.com");
        reqProductDetail.setPrice(BigDecimal.valueOf(30));
        reqProductDetail.setProductDesc("产品描述:霸王duang洗发露");
        reqProductDetail.setProductId("1");
        reqProductDetail.setProductName("霸王洗发水");
        reqProductDetail.setProductURL("产品缩略图:");
        reqProductDetail.setQuantity(5);
        reqProductDetailList.add(reqProductDetail);
        reqOrderSave.setProductDetailList(reqProductDetailList);


        List<ReqPayInfo> reqPayInfos = new ArrayList<>();
        ReqPayInfo reqPayInfo = new ReqPayInfo();
        reqPayInfo.setPayId(PayWayEnum.PAY_WAY_WEICHAT_SCAN.getPayId());
        reqPayInfo.setAmount(test.getOrderAmount());
        reqPayInfos.add(reqPayInfo);

        reqOrderSave.setPayInfos(reqPayInfos);

        APIResponse<RespPreOrder> respPreOrderAPIResponse = this.orderPayService.submitOrder(reqOrderSaveAPIRequest);
        Gson gson = new GsonBuilder().create();
        String json = gson.toJson(respPreOrderAPIResponse);
        System.out.println(json);
        return new ResponseEntity<Object>(respPreOrderAPIResponse, HttpStatus.OK);
    }

    @RequestMapping(value="/aliscancode",method= RequestMethod.POST)
    public ResponseEntity<Object> aliscancode(HttpServletRequest request,@RequestBody ReqOrderSave test){
        APIRequest<ReqOrderSave> reqOrderSaveAPIRequest = new APIRequest<>();
        ReqOrderSave reqOrderSave = new ReqOrderSave();
        reqOrderSaveAPIRequest.setData(reqOrderSave);

        reqOrderSave.setSourceBusinessId("PLACE_BOOKING_BUSINESS_CODE");
        reqOrderSave.setSourceSystemId("PLACE_SYSTEM_CODE");
        reqOrderSave.setChannelId(1);
        reqOrderSave.setContactMobile("13888888888");
        reqOrderSave.setContactName("制哥");
        reqOrderSave.setExtraParam("拓展字段原样返回");
        reqOrderSave.setMchId(2); //此处为城市ID
        reqOrderSave.setNotifyURL(callBack);
        reqOrderSave.setOrderAmount(test.getOrderAmount());  //订单金额100元.
        reqOrderSave.setOrderDescribe("我也不知道买了什么");
        reqOrderSave.setOrderURL("订单缩略图URL");
        reqOrderSave.setOutTradeNo(test.getOutTradeNo());
        reqOrderSave.setPayNote("速不要辣椒");
        reqOrderSave.setPayTimeOut(10);

        reqOrderSave.setUid(810);
        reqOrderSave.setShowURL("订单中心展现的商品详情URL");
      //  reqOrderSave.setBuyerAccount("o5p0hwDiTg8Q8TTkW6GYtlWZVcPA");
        reqOrderSave.setUserClientIp("10.46.131.91, 61.50.248.5");
        // reqOrderSave.setBuyerAccount("oL_y9s22C1flAfP3v7dF3caRWVDg");
        reqOrderSave.setService("service.pay");

        List<ReqProductDetail> reqProductDetailList = new ArrayList<>();
        ReqProductDetail reqProductDetail = new ReqProductDetail();
        reqProductDetail.setShowURL("产品详情URL:http://www.baidu.com");
        reqProductDetail.setPrice(BigDecimal.valueOf(30));
        reqProductDetail.setProductDesc("产品描述:霸王duang洗发露");
        reqProductDetail.setProductId("1");
        reqProductDetail.setProductName("霸王洗发水");
        reqProductDetail.setProductURL("产品缩略图:");
        reqProductDetail.setQuantity(5);
        reqProductDetailList.add(reqProductDetail);
        reqOrderSave.setProductDetailList(reqProductDetailList);


        List<ReqPayInfo> reqPayInfos = new ArrayList<>();
        ReqPayInfo reqPayInfo = new ReqPayInfo();
        reqPayInfo.setPayId(PayWayEnum.PAY_WAY_ALIPAY_SCAN_CODE.getPayId());
        reqPayInfo.setAmount(test.getOrderAmount());
        reqPayInfos.add(reqPayInfo);

        reqOrderSave.setPayInfos(reqPayInfos);

        APIResponse<RespPreOrder> respPreOrderAPIResponse = this.orderPayService.submitOrder(reqOrderSaveAPIRequest);
        Gson gson = new GsonBuilder().create();
        String json = gson.toJson(respPreOrderAPIResponse);
        System.out.println(json);
        return new ResponseEntity<Object>(respPreOrderAPIResponse, HttpStatus.OK);
    }

    @RequestMapping(value="/wxscancode",method= RequestMethod.POST)
    public ResponseEntity<Object> wxscancode(HttpServletRequest request,@RequestBody ReqOrderSave test){
        APIRequest<ReqOrderSave> reqOrderSaveAPIRequest = new APIRequest<>();
        ReqOrderSave reqOrderSave = new ReqOrderSave();
        reqOrderSaveAPIRequest.setData(reqOrderSave);

        reqOrderSave.setSourceBusinessId("PLACE_BOOKING_BUSINESS_CODE");
        reqOrderSave.setSourceSystemId("PLACE_SYSTEM_CODE");
        reqOrderSave.setChannelId(1);
        reqOrderSave.setContactMobile("13888888888");
        reqOrderSave.setContactName("制哥");
        reqOrderSave.setExtraParam("拓展字段原样返回");
        reqOrderSave.setMchId(2); //此处为城市ID
        reqOrderSave.setNotifyURL(callBack);
        reqOrderSave.setOrderAmount(test.getOrderAmount());  //订单金额100元.
        reqOrderSave.setOrderDescribe("我也不知道买了什么");
        reqOrderSave.setOrderURL("订单缩略图URL");
        reqOrderSave.setOutTradeNo(test.getOutTradeNo());
        reqOrderSave.setPayNote("速不要辣椒");
        reqOrderSave.setPayTimeOut(10);

        reqOrderSave.setUid(810);
        reqOrderSave.setShowURL("订单中心展现的商品详情URL");
        //  reqOrderSave.setBuyerAccount("o5p0hwDiTg8Q8TTkW6GYtlWZVcPA");
        reqOrderSave.setUserClientIp("10.46.131.91, 61.50.248.5");
        // reqOrderSave.setBuyerAccount("oL_y9s22C1flAfP3v7dF3caRWVDg");
        reqOrderSave.setService("service.pay");

        List<ReqProductDetail> reqProductDetailList = new ArrayList<>();
        ReqProductDetail reqProductDetail = new ReqProductDetail();
        reqProductDetail.setShowURL("产品详情URL:http://www.baidu.com");
        reqProductDetail.setPrice(BigDecimal.valueOf(30));
        reqProductDetail.setProductDesc("产品描述:霸王duang洗发露");
        reqProductDetail.setProductId("1");
        reqProductDetail.setProductName("霸王洗发水");
        reqProductDetail.setProductURL("产品缩略图:");
        reqProductDetail.setQuantity(5);
        reqProductDetailList.add(reqProductDetail);
        reqOrderSave.setProductDetailList(reqProductDetailList);


        List<ReqPayInfo> reqPayInfos = new ArrayList<>();
        ReqPayInfo reqPayInfo = new ReqPayInfo();
        reqPayInfo.setPayId(PayWayEnum.PAY_WAY_WEICHAT_SCAN_CODE.getPayId());
        reqPayInfo.setAmount(test.getOrderAmount());
        reqPayInfos.add(reqPayInfo);

        reqOrderSave.setPayInfos(reqPayInfos);

        APIResponse<RespPreOrder> respPreOrderAPIResponse = this.orderPayService.submitOrder(reqOrderSaveAPIRequest);
        Gson gson = new GsonBuilder().create();
        String json = gson.toJson(respPreOrderAPIResponse);
        System.out.println(json);
        return new ResponseEntity<Object>(respPreOrderAPIResponse, HttpStatus.OK);
    }

    @RequestMapping(value="/aliscan",method= RequestMethod.POST)
    public ResponseEntity<Object> test1(HttpServletRequest request,@RequestBody ReqOrderSave test){
        APIRequest<ReqOrderSave> reqOrderSaveAPIRequest = new APIRequest<>();
        ReqOrderSave reqOrderSave = new ReqOrderSave();
        reqOrderSaveAPIRequest.setData(reqOrderSave);

        reqOrderSave.setSourceBusinessId("PLACE_BOOKING_BUSINESS_CODE");
        reqOrderSave.setSourceSystemId("PLACE_SYSTEM_CODE");
        reqOrderSave.setChannelId(1);
        reqOrderSave.setContactMobile("13888888888");
        reqOrderSave.setContactName("制哥");
        reqOrderSave.setExtraParam("拓展字段原样返回");
        reqOrderSave.setMchId(2); //此处为城市ID
        reqOrderSave.setNotifyURL(callBack);
        reqOrderSave.setOrderAmount(test.getOrderAmount());  //订单金额100元.
        reqOrderSave.setOrderDescribe("我也不知道买了什么");
        reqOrderSave.setOrderURL("订单缩略图URL");
        reqOrderSave.setOutTradeNo(test.getOutTradeNo());
        reqOrderSave.setPayNote("速不要辣椒");
        reqOrderSave.setUserClientIp("");
        reqOrderSave.setPayTimeOut(1);
        reqOrderSave.setUid(810);
        reqOrderSave.setShowURL("订单中心展现的商品详情URL");
        reqOrderSave.setBuyerAccount("o5p0hwDiTg8Q8TTkW6GYtlWZVcPA");
        reqOrderSave.setUserClientIp("10.46.131.91, 61.50.248.5");
        // reqOrderSave.setBuyerAccount("oL_y9s22C1flAfP3v7dF3caRWVDg");
        reqOrderSave.setService("service.pay");
        reqOrderSave.setAuthCode(test.getAuthCode());

        List<ReqProductDetail> reqProductDetailList = new ArrayList<>();
        ReqProductDetail reqProductDetail = new ReqProductDetail();
        reqProductDetail.setShowURL("产品详情URL:http://www.baidu.com");
        reqProductDetail.setPrice(BigDecimal.valueOf(30));
        reqProductDetail.setProductDesc("产品描述:霸王duang洗发露");
        reqProductDetail.setProductId("1");
        reqProductDetail.setProductName("霸王洗发水");
        reqProductDetail.setProductURL("产品缩略图:");
        reqProductDetail.setQuantity(5);
        reqProductDetailList.add(reqProductDetail);
        reqOrderSave.setProductDetailList(reqProductDetailList);


        List<ReqPayInfo> reqPayInfos = new ArrayList<>();
        ReqPayInfo reqPayInfo = new ReqPayInfo();
        reqPayInfo.setPayId(PayWayEnum.PAY_WAY_ALIPAY_SCAN.getPayId());
        reqPayInfo.setAmount(test.getOrderAmount());
        reqPayInfos.add(reqPayInfo);

        reqOrderSave.setPayInfos(reqPayInfos);

        APIResponse<RespPreOrder> respPreOrderAPIResponse = this.orderPayService.submitOrder(reqOrderSaveAPIRequest);
        Gson gson = new GsonBuilder().create();
        String json = gson.toJson(respPreOrderAPIResponse);
        System.out.println(json);
        return new ResponseEntity<Object>(respPreOrderAPIResponse, HttpStatus.OK);
    }

    @RequestMapping(value="/aliScanRefund",method= RequestMethod.POST)
    public ResponseEntity<Object> aliScanRefund(HttpServletRequest request,@RequestBody ReqOrderRefund test){
        ReqOrderRefund reqOrderRefund = new ReqOrderRefund();
        APIRequest<ReqOrderRefund> orderRefundAPIRequest = new APIRequest<>();
        reqOrderRefund.setSourceBusinessId("PLACE_SYSTEM_CODE");
        reqOrderRefund.setSourceSystemId("PLACE_BOOKING_BUSINESS_CODE");
        reqOrderRefund.setOrderNo(test.getOrderNo());
        reqOrderRefund.setReason("不想去了");
        reqOrderRefund.setUid(810);
        reqOrderRefund.setAmount(new BigDecimal("0.01"));
        reqOrderRefund.setNeedAudit(false); //false不需要人工审核.  true: 需要人工审核, 根据业务需求设置
        reqOrderRefund.setOutTradeNo(test.getOutTradeNo());
        reqOrderRefund.setOutTradeRefundNo(reqOrderRefund.getOutTradeNo());//业务系统退款流水号

        List<ReqRefundProduct> reqRefundProducts = new ArrayList<>();
        ReqRefundProduct refundProduct = new ReqRefundProduct();
        refundProduct.setPrice(new BigDecimal("0.01"));
        refundProduct.setProductId("1");
        refundProduct.setQuantity(1);
        refundProduct.setProductName("duang");
        reqRefundProducts.add(refundProduct);
        reqOrderRefund.setRefundProductList(reqRefundProducts);

        List<ReqRefundPayInfo> reqRefundPayInfoList = new ArrayList<ReqRefundPayInfo>();
        ReqRefundPayInfo rmb = new ReqRefundPayInfo();
        rmb.setPayId(PayWayEnum.PAY_WAY_ALIPAY_SCAN.getPayId());
        rmb.setRefundAmount(test.getAmount());
        reqRefundPayInfoList.add(rmb);

//        reqRefundPayInfoList.add(ages);
        reqOrderRefund.setReqRefundPayInfos(reqRefundPayInfoList);
        orderRefundAPIRequest.setData(reqOrderRefund);
        APIResponse<RefundStatusEnum> apiResponse = orderPayService.refundApply(orderRefundAPIRequest);
        System.out.println(apiResponse.isRet() + "" + apiResponse.getErrmsg());
        return new ResponseEntity<Object>(apiResponse, HttpStatus.OK);
    }


    @RequestMapping(value="/wxScanRefund",method= RequestMethod.POST)
    public ResponseEntity<Object> wxScanRefund(HttpServletRequest request,@RequestBody ReqOrderRefund test){
        ReqOrderRefund reqOrderRefund = new ReqOrderRefund();
        APIRequest<ReqOrderRefund> orderRefundAPIRequest = new APIRequest<>();
        reqOrderRefund.setSourceBusinessId("PLACE_SYSTEM_CODE");
        reqOrderRefund.setSourceSystemId("PLACE_BOOKING_BUSINESS_CODE");
        reqOrderRefund.setOrderNo(test.getOrderNo());
        reqOrderRefund.setReason("不想去了");
        reqOrderRefund.setUid(810);
        reqOrderRefund.setAmount(new BigDecimal("0.01"));
        reqOrderRefund.setNeedAudit(false); //false不需要人工审核.  true: 需要人工审核, 根据业务需求设置
        reqOrderRefund.setOutTradeNo(test.getOutTradeNo());
        reqOrderRefund.setOutTradeRefundNo(reqOrderRefund.getOutTradeNo());//业务系统退款流水号

        List<ReqRefundProduct> reqRefundProducts = new ArrayList<>();
        ReqRefundProduct refundProduct = new ReqRefundProduct();
        refundProduct.setPrice(new BigDecimal("0.01"));
        refundProduct.setProductId("1");
        refundProduct.setQuantity(1);
        refundProduct.setProductName("duang");
        reqRefundProducts.add(refundProduct);
        reqOrderRefund.setRefundProductList(reqRefundProducts);

        List<ReqRefundPayInfo> reqRefundPayInfoList = new ArrayList<ReqRefundPayInfo>();
        ReqRefundPayInfo rmb = new ReqRefundPayInfo();
        rmb.setPayId(PayWayEnum.PAY_WAY_WEICHAT_SCAN.getPayId());
        rmb.setRefundAmount(test.getAmount());
        reqRefundPayInfoList.add(rmb);

//        reqRefundPayInfoList.add(ages);
        reqOrderRefund.setReqRefundPayInfos(reqRefundPayInfoList);
        orderRefundAPIRequest.setData(reqOrderRefund);
        APIResponse<RefundStatusEnum> apiResponse = orderPayService.refundApply(orderRefundAPIRequest);
        System.out.println(apiResponse.isRet() + "" + apiResponse.getErrmsg());
        return new ResponseEntity<Object>(apiResponse, HttpStatus.OK);
    }


    @RequestMapping(value="/orderQuery",method= RequestMethod.POST)
    public ResponseEntity<Object> orderQuery(@RequestBody Order order){
        //支付宝扫描枪订单查询
        OrderExample orderExample = new OrderExample();
        orderExample.createCriteria().andOrderNoEqualTo(order.getOrderNo());
        List<Order> orderList=orderMapper.selectByExample(orderExample);
        AlipayConfig alipayConfig = payConfigService.getAlipayConfig(orderList.get(0).getMchId().toString(), orderList.get(0).getPayId().intValue());
        AliPayTradeQueryReq aliPayTradeQuery = new AliPayTradeQueryReq();
        aliPayTradeQuery.setOut_trade_no(order.getOrderNo());
        APIResponse<AliPayTradeQueryResp> apiResponse=alipayComponent.tradeQuery(aliPayTradeQuery,alipayConfig);
        return new ResponseEntity<Object>(apiResponse, HttpStatus.OK);
    }


    @RequestMapping(value="/wxCloseScan",method= RequestMethod.POST)
    public ResponseEntity<Object> wxCloseScan(@RequestBody Order order){
        return new ResponseEntity<Object>(1, HttpStatus.OK);
    }


    @RequestMapping(value="/alikey",method= RequestMethod.POST)
    public ResponseEntity<Object> alikey(@RequestBody ReqAlipayAccount reqAlipayAccount){
        AlipayAccount alipayAccount = new AlipayAccount();
        alipayAccount.setPrivateKey(AESCoder.decodeContent(reqAlipayAccount.getPrivateKey()));
        alipayAccount.setPublicKey(AESCoder.decodeContent(reqAlipayAccount.getPublicKey()));
        alipayAccount.setAliKey(AESCoder.decodeContent(reqAlipayAccount.getAliKey()));

        return new ResponseEntity<Object>(alipayAccount, HttpStatus.OK);
    }


    @RequestMapping(value="/alikeyencode",method= RequestMethod.POST)
    public ResponseEntity<Object> alikeyencode(@RequestBody ReqAlipayAccount reqAlipayAccount){
        AlipayAccount alipayAccount = new AlipayAccount();
        alipayAccount.setPrivateKey(AESCoder.encodeContent(reqAlipayAccount.getPrivateKey()));


        return new ResponseEntity<Object>(alipayAccount, HttpStatus.OK);
    }


    @RequestMapping(value="/urlcheck",method= RequestMethod.POST)
    public ResponseEntity<Object> urlcheck(@RequestBody ReqAlipayAccount reqAlipayAccount) throws Exception {
        String url="https://mapi.alipay.com/gateway.do?service=notify_verify&partner=2088421220279210&notify_id=19baeeee66948922412bb983f484cb7g8e";
      //  String a=AlipayNotify.checkUrl(url);
        String a=HttpClientUtils.post(url,"");
        System.out.println(a.equals("true"));
        return new ResponseEntity<Object>(1, HttpStatus.OK);
    }

    @RequestMapping(value="/checksign",method= RequestMethod.POST)
    public ResponseEntity<Object> checksign(@RequestBody ReqAlipayAccount reqAlipayAccount) throws Exception {
        AlipayConfig alipayConfig = this.accountService.selectAlipayConfigBySellerIdAndEmail("2088421220279210", "financial6@quncaotech.com");
        String preSignStr="body=预定测试次卡场馆&buyer_email=15914302578&buyer_id=2088502732901038&discount=0.00&gmt_create=2016-11-26 16:31:44&gmt_payment=2016-11-26 16:31:45&is_total_fee_adjust=N&notify_id=22cb622a7a1ca62c3d8ab730f1fac7dg8e&notify_time=2016-11-26 16:31:45&notify_type=trade_status_sync&out_trade_no=23315949268800971780&payment_type=1&price=0.10&quantity=1&seller_email=financial6@quncaotech.com&seller_id=2088421220279210&subject=预定测试次卡场馆&total_fee=0.10&trade_no=2016112621001004030264316021&trade_status=TRADE_SUCCESS&use_coupon=N";
        String sign="K8fl1SfIs3EEMiW7PKM5xFOFlHUW7D2vwKZJTRkdbQfb9cugu9cEfu3K3QqCysUtkxM0JnciMl3aPJ1HK43B62RZ/CJsHc/YJFfe+qYzLROMah6hVYkCOKIHRL0n/ucoInvsdsPC3DD9WLhnU0ZUIIxDiXzFdd92LAop7WJZTy0=";
        boolean isSign = RSA.verify(preSignStr, sign, alipayConfig.getAli_public_key(), "UTF-8");
        return new ResponseEntity<Object>(isSign, HttpStatus.OK);
    }

    @RequestMapping(value="/resend",method= RequestMethod.POST)
    public ResponseEntity<Object> resend(@RequestBody ReqAlipayAccount reqAlipayAccount){
        Gson gson = new GsonBuilder().create();
        java.lang.reflect.Type type = new com.google.common.reflect.TypeToken<BackInfo>() {
        }.getType();
        String result=null;
        BackInfo backInfo = gson.fromJson(result, type);
        if (!(backInfo.getRet() && backInfo.getErrcode().equals(200))) {
            System.out.println("1");
        }else{
            System.out.println("2");
        }
        return new ResponseEntity<Object>(1, HttpStatus.OK);
    }

    @RequestMapping(value="/refundjson",method= RequestMethod.POST)
    public ResponseEntity<Object> refundjson(@RequestBody ReqAlipayAccount reqAlipayAccount){
        String json = "{\n" +
                "    \"data\": {\n" +
                "        \"amount\": 1,\n" +
                "        \"needAudit\": false,\n" +
                "        \"orderNo\": \"23406219364800350768\",\n" +
                "        \"outTradeNo\": \"E23406220327300350740\",\n" +
                "        \"outTradeRefundNo\": \"E23406220327300350740\",\n" +
                "        \"pageNo\": 0,\n" +
                "        \"pageSize\": 20,\n" +
                "        \"refundNotifyURL\": \"\",\n" +
                "        \"refundProductList\": [\n" +
                "            {\n" +
                "                \"price\": 1,\n" +
                "                \"productId\": \"dde9ba59d6202e6d6deb9f67c0a00006\",\n" +
                "                \"productName\": \"18:00:00-19:00:00时段\",\n" +
                "                \"quantity\": 1\n" +
                "            }\n" +
                "        ],\n" +
                "        \"reqRefundPayInfos\": [\n" +
                "            {\n" +
                "                \"payId\": 1,\n" +
                "                \"refundAmount\": 1\n" +
                "            }\n" +
                "        ],\n" +
                "        \"sourceBusinessId\": \"PLACE_BOOKING_BUSINESS_CODE\",\n" +
                "        \"sourceSystemId\": \"PLACE_SYSTEM_CODE\",\n" +
                "        \"uid\": 9003507,\n" +
                "        \"ver\": \"2.3\"\n" +
                "    }\n" +
                "}";

        Gson gson = new GsonBuilder().create();
        Type type = new com.google.common.reflect.TypeToken<APIRequest<ReqOrderRefund>>(){}.getType();
        APIRequest<ReqOrderRefund> orderRefundAPIRequest =   gson.fromJson(json, type);
        APIResponse<RefundStatusEnum> apiResponse = this.orderPayService.refundApply(orderRefundAPIRequest);
        System.out.println(apiResponse.isRet() + "" + apiResponse.getErrmsg());
        return new ResponseEntity<Object>(1, HttpStatus.OK);
    }

    @RequestMapping(value="/asyncTra",method= RequestMethod.POST)
    public ResponseEntity<Object> asyncTra(@RequestBody ReqAlipayAccount reqAlipayAccount){
        //多线程事务
        //获取该批次的流水记录
        List<String> withdrawNoListt = Arrays.asList("209".split(","));
        int updateApplyCount = eWithdrawApplyMapper.updateApplyByWithdrawNos(withdrawNoListt);
//                String[] strlist = withdrawBatchList.get(0).getWithdrawNos().split(",");
//                List<Integer> withdrawNoList = new ArrayList<Integer>();
//                for(String str : strlist) {
//                    withdrawNoList.add(Integer.parseInt(str));
//                }
//                WithdrawApplyExample withdrawApplyExample = new WithdrawApplyExample();
//                withdrawApplyExample.createCriteria().andWithdrawNoIn(withdrawNoList);
//                WithdrawApply withdrawApply = new WithdrawApply();
//                withdrawApply.setStatus((byte)0);
//                int updateApplyCount = withdrawApplyMapper.updateByExampleSelective(withdrawApply,withdrawApplyExample);
        System.out.println("更新提现申请表数："+updateApplyCount);
        return new ResponseEntity<Object>(1, HttpStatus.OK);
    }

    @RequestMapping(value="/batchTransByWeChat",method= RequestMethod.POST)
    public ResponseEntity<Object> batchTransByWeChat(@RequestBody WithdrawPayInfo withdrawPayInfo){
        ReqWithdrawFormData reqWithdrawTransfer = new ReqWithdrawFormData();
        List<WithdrawPayInfo> withdrawPayInfoList = new ArrayList<WithdrawPayInfo>();
        WithdrawPayInfo payInfo = new WithdrawPayInfo();
        payInfo.setAccountNo("ocJpsv0ZjA8JLKkSHZKmy3EQDX-Q");
        payInfo.setAmount(new BigDecimal("1.00"));
        payInfo.setApplyNo("63421481615348348");
        payInfo.setPayAmount(new BigDecimal("1.00"));
        payInfo.setPayOpInfo("测试打款");
        payInfo.setWithdrawNo("218");
        payInfo.setPayType((byte)2);
        withdrawPayInfoList.add(payInfo);
        reqWithdrawTransfer.setWithdrawPayInfos(withdrawPayInfoList);
        APIResponse apiResponse=orderPayService.batchTrans(reqWithdrawTransfer);

        return new ResponseEntity<Object>(apiResponse, HttpStatus.OK);
    }


    @RequestMapping(value="/batchTransByAli",method= RequestMethod.POST)
    public ResponseEntity<Object> batchTransByAli(@RequestBody WithdrawPayInfo withdrawPayInfo) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ReqWithdrawFormData reqWithdrawTransfer = new ReqWithdrawFormData();
        List<WithdrawPayInfo> withdrawPayInfoList = new ArrayList<WithdrawPayInfo>();
        WithdrawPayInfo payInfo = new WithdrawPayInfo();
        payInfo.setAccountNo("15914302578");
        payInfo.setAmount(new BigDecimal("1.00"));
        payInfo.setApplyNo("63421481599236264");
        payInfo.setApplyTime(sdf.parse("2016-12-13 11:20:36"));
        payInfo.setName("林荣涛");
        payInfo.setPayAmount(new BigDecimal("1.00"));
        payInfo.setPayOpInfo("测试打款");
        payInfo.setWithdrawNo("213");
        payInfo.setPayType((byte)1);
        withdrawPayInfoList.add(payInfo);
        reqWithdrawTransfer.setWithdrawPayInfos(withdrawPayInfoList);
        APIResponse apiResponse=orderPayService.batchTrans(reqWithdrawTransfer);

        return new ResponseEntity<Object>(apiResponse, HttpStatus.OK);
    }

    @RequestMapping(value="/deleteKey",method= RequestMethod.GET)
    public ResponseEntity<Object> deleteKey(Integer clubId) throws ParseException {
        RedisKey key = new RedisKey(RedisConstants.CLUB_FAMILY_KEY, clubId + ":withdrawals");
        orderPayRedisTemplate.delteKey(key);
        return new ResponseEntity<Object>(1, HttpStatus.OK);
    }

    @RequestMapping(value="/btnStatusQuery",method= RequestMethod.GET)
    public ResponseEntity<Object> btnStatusQuery(String batchNo) {
        //支付宝扫描枪订单查询
        AlipayConfig alipayConfig = payConfigService.getAlipayConfig("2", 1);


        APIResponse apiResponse=alipayComponent.btnStatusQuery(batchNo,alipayConfig);
        return new ResponseEntity<Object>(apiResponse, HttpStatus.OK);
    }

    @RequestMapping(value="/dateformat",method= RequestMethod.GET)
    public ResponseEntity<Object> dateformat(String batchNo) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddhhmmss");

        String date = "20170209164637";
        Date time = simpleDateFormat.parse(simpleDateFormat.format(sdf1.parse(date)));
        return new ResponseEntity<Object>(time, HttpStatus.OK);
    }

    @RequestMapping(value="/singleOrderQuery",method= RequestMethod.GET)
    public ResponseEntity<Object> singleOrderQuery(String batchNo) throws ParseException {
        AlipayConfig alipayConfig = payConfigService.getAlipayConfig("2", 1);
        AliRespQueryTrade aliRespQueryTrade = alipayComponent.queryTrade("31174557585801272711", alipayConfig);
        return new ResponseEntity<Object>(aliRespQueryTrade, HttpStatus.OK);
    }
    @RequestMapping(value="/maintainPayRecord",method= RequestMethod.POST)
    public APIResponse maintainPayRecord(String key){
        if (!"zk".equals(key)) {
            return APIResponse.returnFail("");
        }
        int pageNum = 0;
        int pageSize = 100;
        int listSize;
        do {
            PayRecordExample example = new PayRecordExample();
            PayRecordExample.Criteria criteria = example.createCriteria();

            example.setPage(new Page(pageNum*pageSize, pageSize));

            List<PayRecord> payRecordList = payRecordMapper.selectByExample(example);
            for (PayRecord payRecord : payRecordList) {
                processPayRecord(payRecord);
            }
            listSize = payRecordList.size();
            System.out.println(pageNum + "-" + listSize);
            pageNum++;
        } while (listSize > 0);
        return APIResponse.returnSuccess();
    }

    private void processPayRecord(PayRecord payRecord) {
        try {
            if (payRecord.getPayState() == 0 || payRecord.getPayState() == 5) {
                if (!StringUtil.isBlankOrNull(payRecord.getSellerId())) {
                    payRecord.setSellerId(null);
                    payRecord.setSellerAccount(null);
                    payRecordMapper.updateByPrimaryKey(payRecord);
                }
            }
            if (payRecord.getPayState() == 1) {
                if (canResetValue(payRecord.getSellerAccount(), payRecord.getPayId())) {
                    TSNRecordExample example = new TSNRecordExample();
                    TSNRecordExample.Criteria criteria = example.createCriteria();
                    criteria.andTsnEqualTo(payRecord.getTsn());

                    List<TSNRecord> tsnRecordList = tsnRecordMapper.selectByExample(example);
                    if (tsnRecordList.size() <= 0) {
                        return;
                    }
                    TSNRecord tsnRecord = tsnRecordList.get(0);
                    String[] arr = tsnRecord.getRespDate().split("&");
                    for (String s : arr) {
                        if (s.contains("seller_id")) {
                            payRecord.setSellerId(s.split("=")[1]);
                        }
                        if (s.contains("seller_email")) {
                            payRecord.setSellerAccount(s.split("=")[1]);
                        }
                    }

                    payRecordMapper.updateByPrimaryKey(payRecord);
                }
            }
        } catch (Exception e) {

        }
    }

    private boolean canResetValue(String sellerAccount, Integer payId) {
        if (StringUtil.isBlankOrNull(sellerAccount)) {
            return true;
        }
        if (payId.equals(PayWayEnum.PAY_WAY_ALIPAY.getPayId()) || payId.equals(PayWayEnum.PAY_WAY_ALIPAY_SCAN.getPayId()) || payId.equals(PayWayEnum.PAY_WAY_ALIPAY_SCAN.getPayId())) {
            if (sellerAccount.startsWith("wx")) {
                return true;
            }
        }
        return false;
    }

}
